package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.base.domain.Attendance;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.domain.*;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.*;
import cn.wolfcode.trip.base.service.*;
import cn.wolfcode.trip.base.util.JsonResult;
import com.github.pagehelper.PageInfo;
import jdk.internal.org.objectweb.asm.commons.TryCatchBlockSorter;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IAttendanceService attendanceService;
    @Autowired
    private IProductByUserService productByUserService;
    @Autowired
    private IOrderByUserService orderByUserService;
    @Autowired
    private IFriendDynamicsService friendDynamicsService;

    //获取用户朋友们的动态
    @GetMapping("{UserId}/friendDynamics")
    public PageInfo getFriendDynamics(FriendQuery qo) {
        qo.setOrderBy("fd.creatTime desc");
        return friendDynamicsService.query(qo);
    }

    //发布动态
    @PostMapping("friendDynamics")
    public JsonResult AddFriendDynamics(FriendDynamics fd) {
        JsonResult json = new JsonResult();
        try {
            friendDynamicsService.addFriendDynamics(fd);
        } catch (Exception e) {
            json.mark(e.getMessage());
        }
        return json;
    }

    //获取所有的已购买订单
    @GetMapping("{userId}/orders")
    public PageInfo getOrder(OrderQuery qo) {
        return orderByUserService.query(qo);
    }

    //点击加入购物车
    @PostMapping("{userId}/addCars")
    public JsonResult addCar(@PathVariable("userId") Long userId, Long productId) {
        JsonResult json = new JsonResult();
        try {
            productByUserService.add(userId, productId);
        } catch (Exception e) {
            json.mark(e.getMessage());
        }
        return json;
    }

    //点击移出购物车
    @PostMapping("{userId}/deleteCars")
    public JsonResult deleteCar(@PathVariable("userId") Long userId, Long productCarId) {
        JsonResult json = new JsonResult();
        try {
            productByUserService.deleteByCarId(userId, productCarId);
        } catch (Exception e) {
            json.mark(e.getMessage());
        }
        return json;
    }

    //获取用户的购物车信息
    @GetMapping("{userId}/productByUsers")
    public PageInfo getShopCarById(ProductQuery qo) {
        PageInfo pageInfo = productByUserService.query(qo);
        return pageInfo;
    }

    //支付积分
    @GetMapping("{userId}/attendances/integrals")
    public JsonResult getIntegralsByUserId(IntegralQuery qo, Long[] productId, int[] productNumber, Long[] carId) {
        JsonResult json = new JsonResult();
        try {
            System.out.println(qo.getTotal());
            attendanceService.pay(qo, productId, productNumber, carId);
        } catch (Exception e) {
            json.mark(e.getMessage());
        }
        return json;
    }

    //获取用户的签到信息
    @GetMapping("{userId}/attendances")
    public Attendance getAttendance(@PathVariable Long userId) {
        Attendance attendance = attendanceService.get(userId);
        return attendance;
    }

    //修改用户的签到信息
    @PostMapping("{userId}/attendances")
    public Integer saveOrUpdate(@PathVariable Long userId, Date date) {
        Attendance attendance = attendanceService.get(userId);
        System.out.println(new Date().compareTo(attendance.getLastSignTime()));
        return attendanceService.saveOrUpdate(attendance, date);
    }

    @Autowired
    private IInformationService informationService;

    @Autowired //查询评论用
    private IStrategyCommentService strategyCommentService;

    @PostMapping
    public JsonResult register(User user) {
        JsonResult result = new JsonResult();
        try {
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @PutMapping("/{id}")
    public JsonResult update(User user) {
        JsonResult result = new JsonResult();
        try {
            userService.update(user);
            result.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}")
    public JsonResult get(@PathVariable Long id) {
        JsonResult result = new JsonResult();
        try {
            result.setData(userService.get(id));
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping("/{authorId}/travels")
    public PageInfo listTravels(TravelQueryObject qo) {
        PageInfo pageInfo = travelService.queryForList(qo);
        return pageInfo;
    }

    /**
     * 获取未读的不同type通知条数
     * 资源:users/{id}/infoUnreadNum
     * 方法:get
     * 参数:无
     * 返回:int
     */
    @GetMapping("{userId}/infoUnreadNum")
    public int getInformationNum(@PathVariable Long userId, Integer type) {
        return informationService.getUnReadInfoNums(userId, type);
    }

    /**
     * 获取所有的信息,返回一个pageInfo
     * 资源:users/{id}/informations
     * 方法:get
     * 参数:consume:json
     * 返回:pageInfo对象.
     */
    @GetMapping(value = "{userId}/informations", produces = "application/json")
    public PageInfo<Map> listAllInformation(MessageQuery qo) {
        return informationService.listInfoByUserId(qo);
    }

    /**
     * 读取消息
     * 资源:users/{id}/informations/{inforId}
     * 方法:put
     * 参数:路径参数
     * 返回:JsonResult.
     */
    @PutMapping(value = "{userId}/informations/{inforId}")
    public JsonResult readInformation(@PathVariable Long userId, @PathVariable Long inforId) {
        JsonResult result = new JsonResult();
        try {
            result.setData(informationService.readInfo(userId, inforId));
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 更新所有的不同种类的未读消息已读
     *
     * @param :userId:用户的id
     * @param :InformationQuery:查询对象
     * @return: jsonResult
     */
    @PutMapping(value = "{userId}/informations")
    public JsonResult readInformations(InformationQuery qo) {
        JsonResult result = new JsonResult();
        try {
            informationService.batchUpdateInfoRead(qo);
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 获取所有的用户信息,分页
     *
     * @param qo
     * @return
     */
    @GetMapping
    public PageInfo<User> getAllUser(UserQuery qo) {
        return userService.listAll(qo);
    }

    /**
     * 保存某个关注信息
     * 资源 /{userId}/{followId}
     * 请求方式 Post
     * 请求参数 followId
     * 返回结果 无
     */
    @PostMapping("/{userId}/{followId}")
    public void saveByUserIdAndFollowId(@PathVariable("userId") Long userId, @PathVariable("followId") Long followId) {
        userService.saveByUserIdAndFollowId(userId, followId);
    }

    /**
     * 查询用户之间的关系(是否已关注)
     * 资源 /{userId}/{followId}
     * 请求方式 Post
     * 请求参数 userId,followId
     * 返回结果 JsonResult
     */
    @GetMapping("/{userId}/{followId}")
    public JsonResult eachOrtherRelations(@PathVariable("userId") Long userId, @PathVariable("followId") Long followId) {
        JsonResult result = new JsonResult();
        Integer i = userService.selectRelationsByUserIdAndFollowID(userId, followId);
        if (i != 0) {
            return result;
        } else {
            result.mark("关注失败");
            return result;
        }
    }

    /**
     * 取消对某个人的关注
     * 资源    /{followId}
     * 请求方式 delete
     * 请求参数 followId
     * 返回结果 无
     */
    @DeleteMapping("/{followId}")
    public void deleteRelation(@PathVariable("followId") Long followId) {
        userService.deleteRelation(followId);
    }

    /**
     * 查询某个用户的粉丝数
     * 资源 /fans/{userId} fans  没有意义,用于区分方法
     * 请求方式 get
     * 请求参数 userId
     * 返回结果 int
     */
    @GetMapping("/fans/{userId}")
    public int getFansByUserId(@PathVariable("userId") Long userId) {
        return userService.getFansByUserId(userId);
    }

    /**
     * 查询某个用户的关注数
     * 资源 /follows/{followId} follows 没有意义,用于区分方法
     * 请求方式 get
     * 请求参数 followId
     * 返回结果 int
     */
    @GetMapping("/follows/{followId}")
    public int getFollowsByFollowId(@PathVariable("followId") Long followId) {
        return userService.getFollowsByFollowId(followId);
    }

    /**
     * 查询指定用户下的所有评论信息
     * 资源 /{userId}/strategyComments
     * 请求方式 get
     * 请求参数 qo
     * 返回结果 PageInfo
     *
     * @param qo
     * @return
     */
    @GetMapping("/{user.id}/strategyComments")
    public PageInfo<Strategy> listCommonds(StrategyQueryObject qo) {
        PageInfo pageInfo = strategyCommentService.query(qo);
        return pageInfo;
    }

    /**
     * 查询指定用户的评价信息条数
     * 资源 /{userId}/strategyComments/nums
     * 请求方式 get
     * 请求参数 userId
     * 返回结果 int
     */
    @GetMapping("/{userId}/strategyComments/nums")
    public int selectStrategyCommentsNums(@PathVariable("userId") Long userId) {
        return strategyCommentService.selectStrategyCommentsNums(userId);
    }

    /**
     * 查询指定用户的游记条数
     * 资源 /{userId}/travels/nums
     * 请求方式 get
     * 请求参数 userId
     * 返回结果 int
     */
    @GetMapping("/{userId}/travels/nums")
    public int selectTravelsNums(@PathVariable("userId") Long userId) {
        return travelService.selectTravelsNums(userId);
    }

    /**
     * 获取一个用户所有的赞未读的排到上面
     * 资源:users/{authorId}/informations
     * 方式:get
     * 参数:type 0, 1,2, 3, 4, 5
     * 返回:pageInfo
     */
    @GetMapping("{userId}/informations")
    public PageInfo listUserInfo(InformationQuery qo) {
        return informationService.listForInfo(qo);
    }


    /**
     * 获取一个用户可能感兴趣的人
     * 资源:travelers/{userId}
     * 方式:get
     * 参数:type 0, 1,2, 3, 4, 5
     * 返回:pageInfo
     */
    @GetMapping("travelers/{userId}")
    public List<User> listTravelersById(@PathVariable Long userId) {
        return userService.listTravelersById(userId);
    }


}
